<template>
  <div class="zheng">
    <div class="login-container">
      <!-- 左侧面板保持不变 -->
      <div class="left-panel">
        <h1 class="login-title">登录</h1>
        <p class="sub-title">阿里云APP/支付宝/钉钉 </p>
        <img src="@/assets/aly.png" alt="登录二维码" class="qrcode" />
        <div class="other-methods">
          <p class="method-label">其他方式</p>
          <div class="method-icons">
            <div class="icon alipay">支</div>
            <div class="icon taobao">淘</div>
            <div class="icon icon-1688">1688</div>
            <div class="icon weibo">微</div>
            <div class="icon dingtalk">钉</div>
          </div>
        </div>
      </div>
      
      <!-- 右侧面板优化 -->
      <div class="right-panel">
        <div class="tab-bar">
          <span class="tab active" @click="switchTab('account')">账密登录</span>
          <span class="tab" @click="switchTab('phone')">手机号登录</span>
          <button v-if="showLogin" @click="goToRegister" class="register-link">
            前往注册
            <ArrowRight style="width: 1em; height: 1em; margin-right: 8px" />
          </button>
        </div>
        
        <!-- 登录表单使用card组件美化 -->
        <el-card class="login-card">
          <div v-if="activeTab === 'account'">
            <el-input
              v-model="username"
              class="login-input"
              placeholder="请输入账号"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
            
            <el-input
              v-model="password"
              class="login-input"
              placeholder="请输入密码"
              :type="passwordVisible ? 'text' : 'password'"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
              <template #suffix>
                <span class="eye-icon" @click="togglePasswordVisibility">
                  {{ passwordVisible ? '👁️' : '👁️‍🗨️' }}
                </span>
              </template>
            </el-input>
            
            <el-button type="primary" class="login-btn" @click="handleLogin">
              立即登录
            </el-button>
            
            <div class="links">
              <a href="#" @click.prevent="handleForgotUsername">忘记登录名</a>
              <a href="#" @click.prevent="handleForgotPassword">忘记密码</a>
              <a href="#" @click.prevent="handleRAMLogin">RAM登录</a>
            </div>
          </div>
          
          <div v-else>
            <!-- 手机号登录表单 -->
            <el-input
              v-model="phoneNumber"
              class="login-input"
              placeholder="请输入手机号"
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
            
            <div class="input-group">
              <el-input
                v-model="verifyCode"
                class="login-input"
                placeholder="请输入验证码"
                style="width: 60%; display: inline-block;"
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
              <el-button 
                :disabled="countdown > 0" 
                @click="getVerifyCode"
                class="verify-code-btn"
                :style="{ width: '38%; display: inline-block; margin-left: 5px' }"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </el-button>
            </div>
            
            <el-button type="primary" class="login-btn" @click="handlePhoneLogin">
              立即登录
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { ArrowRight, User, Lock, Phone, Message } from '@element-plus/icons-vue'
import axios from 'axios'  // 导入Axios
//import { ArrowRight, User, Lock, Phone, Message } from '@element-plus/icons-vue'
// 创建API实例
const api = axios.create({
  baseURL: 'http://localhost:5000/api'  // 后端服务地址
})

export default {
  name: 'LoginView',
  components: {
    ArrowRight,
    User,
    Lock,
    Phone,
    Message
  },
  data() {
    return {
      username: '',
      password: '',
      phoneNumber: '',
      verifyCode: '',
      showLogin: true,
      activeTab: 'account',
      passwordVisible: false,
      countdown: 0,
      timer: null
    }
  },
  mounted() {
    // 优化后的路由检查逻辑
    this.checkRouteAndSetLoginStatus();
  },
  methods: {
    switchTab(tab) {
      this.activeTab = tab;
    },
    
    togglePasswordVisibility() {
      this.passwordVisible = !this.passwordVisible;
    },
   // 账号密码登录
    handleLogin() {
      if (!this.username || !this.password) {
        this.$message.warning('请输入账号和密码');
        return;
      }
       //前端发送登录请求的路径,需要与后端接口路径匹配
      // 使用修正后的 baseURL 和正确的参数
  api.post('/auth/login/account', {
    identifier: this.username,  // 后端期望的参数名
    password: this.password
  })
  .then(response => {
    this.$message.success('登录成功');
    sessionStorage.setItem('user', JSON.stringify(response.data.user));
    localStorage.setItem('jwt_token', response.data.token); // 关键：存入localStorage
    this.$router.push('/LoginhuihuaView');
  })
  .catch(error => {
    const msg = error.response?.data?.error || '登录失败，请重试';
    this.$message.error(msg);
  });
    },
    
    goToRegister() {
      sessionStorage.setItem('showLogin', '1');
      this.$router.push('/LoginELview')
    .catch(error => {
      console.error('路由跳转失败:', error);
      this.$message.error('无法跳转到注册页面，请刷新后重试');
      
      // 可选：提供备用跳转方式
      window.location.href = '/LoginELview';
    });
    },
    
    handleForgotUsername() {
      this.$message.info('跳转到找回登录名页面');
      this.$router.push('/forgot-username');
    },
    
    handleForgotPassword() {
      this.$message.info('跳转到找回密码页面');
      this.$router.push('/Forgot-password');
    },
    
    handleRAMLogin() {
      this.$message.info('跳转到RAM登录页面');
      this.$router.push('/ram-login');
    },
    // 登录成功后（例如后端返回token）添加存储令牌的代码
     login() {
      axios.post('/api/login', { username: this.username, password: this.password })
      .then(res => {
      //const { token } = response.data; 
      console.log('res.data',res.data);
      
      localStorage.setItem('jwt_token', res.data.token); // 关键：存入localStorage
      this.$router.push('/LoginhuihuaView'); // 跳转到聊天页
    });
     },
    // 优化后的路由检查逻辑
    checkRouteAndSetLoginStatus() {
      const loginPath = '/LoginELview';
      if (this.$route.path === loginPath) {
        this.showLogin = true;
      }
    },
    beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
  }
}
</script>

<style>
.zheng {
  width: 90%;
  max-width: 1200px;
  border: 1px solid #e5e5e5;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  background-image: url('../assets/天空1.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  width: calc(100% - 200px);
  height:100%;
}
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  font-family: "Microsoft YaHei", sans-serif;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
}

.left-panel {
  flex: 0 0 40%;
  padding: 30px;
  box-sizing: border-box;
  border-right: 1px solid #e5e5e5;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.login-title {
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 12px;
}

.sub-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 24px;
}

.qrcode {
  width: 180px;
  height: 180px;
  border: 1px solid #e5e5e5;
  padding: 10px;
  margin-bottom: 24px;
}

.other-methods {
  width: 100%;
}

.method-label {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
  display: block;
}

.method-icons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.3s;
}

.right-panel {
  flex: 1;
  padding: 30px;
  box-sizing: border-box;
}

.tab-bar {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
  padding-bottom: 10px;
}

.tab {
  font-size: 18px;
  padding: 10px 20px;
  cursor: pointer;
  color: #333;
  transition: color 0.3s;
  border-bottom: 2px solid transparent;
}

.tab.active {
  color: #1677ff;
  border-bottom-color: #1677ff;
}

.register-link {
  color: #1677ff;
  text-decoration: none;
  font-size: 14px;
  margin-left: auto;
  display: flex;
  align-items: center;
}

.login-card {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  padding: 30px;
  background-image: url('../assets/sky1.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  width: calc(100% - 200px);
  height:100%;
}

.login-input {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  margin-top: 20px;
}

.links {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-top: 10px;
}

.links a {
  color: #666;
  text-decoration: none;
  transition: color 0.3s;
}

.links a:hover {
  color: #1677ff;
}

.verify-code-btn {
  padding: 0 10px;
}


</style>